package org.example.algorithm.array;

public class TwoSumMediumSolution {

    //二分查找
    public int[] twoSum(int[] numbers, int target) {
        for (int i=0;i<numbers.length;i++) {
            int low = i+1;
            int high = numbers.length - 1;
            while (low <= high) {
                int middle = (low + high) / 2;
                if (target - numbers[i] > numbers[middle]) {
                    low = middle+1;
                } else if(target - numbers[i] < numbers[middle]) {
                    high = middle-1;
                } else {
                    return new int[]{i, middle};
                }
            }
        }
        return new int[0];
    }

    //双指针
    public int[] twoSum2(int[] numbers, int target) {
        int startCur = 0;
        int endCur = numbers.length - 1;
        while (startCur < endCur) {
            if (numbers[startCur] + numbers[endCur] > target) {
                endCur--;
            } else if (numbers[startCur] + numbers[endCur] < target) {
                startCur++;
            } else {
                return new int[]{startCur, endCur};
            }
        }
        return new int[0];
    }

    public static void main(String[] args) {
        int[] numbers = {2, 5, 8, 17};
        int target = 13;
        TwoSumMediumSolution solution = new TwoSumMediumSolution();
        int[] res = solution.twoSum(numbers, target);
        for (int i=0;i<res.length;i++) {
            System.out.println(res[i]);
        }
    }
}
